package cn.itsource.hrm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

//资源服务配置
//@Configuration
//开启资源服务配置
//@EnableResourceServer
//开启方法授权
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyResourceServerConfig_bak extends ResourceServerConfigurerAdapter {

    //1.资源服务安全配置
    /*@Bean
    public ResourceServerTokenServices tokenServices(){
        //使用远程服务请求授权服务器校验token ， 即：资源服务和授权服务器不在一个主机
        RemoteTokenServices services = new RemoteTokenServices();
        //授权服务地址 , 当浏览器访问某个资源时就会调用该远程授权服务地址去校验token
        //要求请求中必须携带token
        services.setCheckTokenEndpointUrl("http://localhost:4020/oauth/check_token");
        //客户端id，对应认证服务的客户端详情配置的clientId
        services.setClientId("admin");
        //密钥，对应认证服务的客户端详情配置的clientId
        services.setClientSecret("1");
        return services;
    }*/
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //配置资源id，对应oauth_client_details表中resource_ids
        resources.resourceId("systemId");
        //远程发请求去获取token中用户和权限
        //resources.tokenServices(tokenServices());
        resources.tokenStore(tokenStore());
    }
    private String key = "itsource_hrm&%%$##@@#%%%";
    //转换器
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){

        //创建
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设置秘钥
        jwtAccessTokenConverter.setSigningKey(key);
        return jwtAccessTokenConverter;
    }
    //构造jwttokenstore
    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    //2 资源服务的资源的授权配置，比如那些资源放行，那些资源需要什么权限等等
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                //关闭跨域伪造检查
                .and().csrf().disable();
    }
}